import { CandlestickData } from '../components/CandlestickChart';

// 生成模拟的蜡烛图数据
export const generateCandlestickData = (
  basePrice: number = 0.00001,
  days: number = 30
): CandlestickData[] => {
  const data: CandlestickData[] = [];
  let currentPrice = basePrice;
  
  for (let i = 0; i < days; i++) {
    const date = new Date();
    date.setDate(date.getDate() - (days - i));
    
    // 生成随机的价格变动 (-5% 到 +5%)
    const volatility = 0.05;
    const priceChange = (Math.random() - 0.5) * 2 * volatility;
    
    const open = currentPrice;
    const change = open * priceChange;
    const close = open + change;
    
    // 生成高低价
    const high = Math.max(open, close) + (Math.random() * Math.abs(change) * 0.5);
    const low = Math.min(open, close) - (Math.random() * Math.abs(change) * 0.5);
    
    // 生成交易量
    const volume = Math.floor(Math.random() * 1000000) + 100000;
    
    data.push({
      time: date.toLocaleDateString(),
      open: Math.max(0, open),
      high: Math.max(0, high),
      low: Math.max(0, low),
      close: Math.max(0, close),
      volume
    });
    
    currentPrice = close;
  }
  
  return data;
};

// 基于交易历史生成真实的蜡烛图数据
export const generateCandlestickFromTrades = (
  trades: Array<{
    price: number;
    amount: number;
    timestamp: string;
    type: 'buy' | 'sell';
  }>,
  interval: 'hour' | 'day' = 'day'
): CandlestickData[] => {
  if (trades.length === 0) {
    return [];
  }
  
  // 按时间间隔分组交易
  const groupedTrades = new Map<string, typeof trades>();
  
  trades.forEach(trade => {
    const date = new Date(trade.timestamp);
    let key: string;
    
    if (interval === 'hour') {
      key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:00`;
    } else {
      key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }
    
    if (!groupedTrades.has(key)) {
      groupedTrades.set(key, []);
    }
    groupedTrades.get(key)!.push(trade);
  });
  
  const candlestickData: CandlestickData[] = [];
  
  // 为每个时间间隔生成蜡烛图数据
  for (const [timeKey, periodTrades] of groupedTrades.entries()) {
    if (periodTrades.length === 0) continue;
    
    // 按时间排序
    periodTrades.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
    
    const open = periodTrades[0].price;
    const close = periodTrades[periodTrades.length - 1].price;
    const high = Math.max(...periodTrades.map(t => t.price));
    const low = Math.min(...periodTrades.map(t => t.price));
    const volume = periodTrades.reduce((sum, t) => sum + t.amount, 0);
    
    candlestickData.push({
      time: timeKey,
      open,
      high,
      low,
      close,
      volume
    });
  }
  
  // 按时间排序
  candlestickData.sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
  
  return candlestickData;
};
